/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.fresh.bus.canoe.session.support;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fresh.bus.canoe.session.Role;
import com.fresh.bus.canoe.session.Session;
import com.fresh.bus.canoe.session.SessionRoleManager;

/**
 *
 * @author panzd
 */
public class DefaultSessionRoleManager implements SessionRoleManager {
	
	 private static final Logger log = LoggerFactory.getLogger(DefaultSessionRoleManager.class);
    private ConcurrentMap<Role, Session> sessionMap;
    private ConcurrentMap<String, Role> roleMap;
    /**
     * @return the sessionMap
     */
    protected ConcurrentMap<Role, Session> getSessionMap() {
        return sessionMap;
    }

    /**
     * @return the roleMap
     */
    protected ConcurrentMap<String, Role> getRoleMap() {
        return roleMap;
    }

    public DefaultSessionRoleManager() {
        sessionMap = new ConcurrentHashMap<Role, Session>();
        roleMap = new ConcurrentHashMap<String, Role>();
    }

    @Override
    public Role getRoleById(String id) {
        return getRoleMap().get(id);
    }

    @Override
    public Collection<Role> getAll() {
        return getSessionMap().keySet();
    }

    @Override
    public void join(Role role, Session session) {
        if(role == null || session == null) return;

        if(!role.equals(session.getRole()))
        {
            session.setRole(role);
        }

        Session lastSession = getSession(role);
        if(session != lastSession)
        {
            if(lastSession != null)
            {
                lastSession.setRole(null);
            }

            getSessionMap().put(role, session);
            getRoleMap().put(role.getId(), role);
        }
    }

    @Override
    public void exit(Role user) {
        if(user == null)
        {
            return;
        }

        Session session = getSession(user);
        if(session != null)
        {
            session.setRole(null);
            getSessionMap().remove(user);
            getRoleMap().remove(user.getId());
        }
    }

    @Override
    public Session getSession(String id) {
    	try{
        	Role user = this.getRoleById(id);
            return getSessionMap().get(user);
    	}catch(Exception e){
    		log.info("Try to get session of id[" + id + "]:" + e.getMessage() +"failed");
    		return null;
    	}
    }
    
    @Override
    public Session getSession(Role user) {
        return getSessionMap().get(user);
    }    
}
